import { Component, OnInit } from '@angular/core';
import { NbAuthJWTToken, NbAuthService } from '@nebular/auth';
import { UserService } from '@nx-chat/common/service';

@Component({
  selector: 'header-user',
  templateUrl: './header-user.component.html',
  styleUrls: ['./header-user.component.scss']
})
export class HeaderUserComponent implements OnInit {
  public user: any;
  public tokenUser: any;
  public userMenu = [{ title: 'Log out', link: '/auth/login' }];

  constructor(
    private _authService: NbAuthService,
    private _userService: UserService,
  ) {
    this._authService.onTokenChange().subscribe((token: NbAuthJWTToken) => {
      if (token.isValid()) {
        this.user = token.getPayload();
      }
    });

    this._authService.getToken().subscribe((token: NbAuthJWTToken) => {
      this.tokenUser = token.getPayload();
    })
  }

  ngOnInit() {
    this._userService.getUserById(this.tokenUser.sub).subscribe((user) => (
      this.user = {
        name: user.name,
        avatar: user.avatar,
      }
    ));
  }
}
